package com.app.trafficclient.WoDeZuoJia;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.app.trafficclient.R;
import com.app.trafficclient.util.GetUrl;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragmentYuanChengKongZhi.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragmentYuanChengKongZhi#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentYuanChengKongZhi extends Fragment implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public FragmentYuanChengKongZhi() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragmentYuanChengKongZhi.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentYuanChengKongZhi newInstance(String param1, String param2) {
        FragmentYuanChengKongZhi fragment = new FragmentYuanChengKongZhi();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    private TextView yuanChengTvQiDong1;
    private TextView yuanChengTvTingZhi1;

    private TextView yuanChengTvQiDong2;
    private TextView yuanChengTvTingZhi2;

    private TextView yuanChengTvQiDong3;
    private TextView yuanChengTvTingZhi3;

    private TextView yuanChengTvQiDong4;
    private TextView yuanChengTvTingZhi4;

    TextView[] textViews;
    RequestQueue requestQueue;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_yuan_cheng, container, false);
        yuanChengTvQiDong1 = (TextView) view.findViewById(R.id.yuanCheng_tv_qiDong1);
        yuanChengTvTingZhi1 = (TextView) view.findViewById(R.id.yuanCheng_tv_tingZhi1);
        yuanChengTvQiDong2 = (TextView) view.findViewById(R.id.yuanCheng_tv_qiDong2);
        yuanChengTvTingZhi2 = (TextView) view.findViewById(R.id.yuanCheng_tv_tingZhi2);
        yuanChengTvQiDong3 = (TextView) view.findViewById(R.id.yuanCheng_tv_qiDong3);
        yuanChengTvTingZhi3 = (TextView) view.findViewById(R.id.yuanCheng_tv_tingZhi3);
        yuanChengTvQiDong4 = (TextView) view.findViewById(R.id.yuanCheng_tv_qiDong4);
        yuanChengTvTingZhi4 = (TextView) view.findViewById(R.id.yuanCheng_tv_tingZhi4);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        textViews = new TextView[]{yuanChengTvQiDong1,yuanChengTvTingZhi1,yuanChengTvQiDong2,yuanChengTvTingZhi2,
                                   yuanChengTvQiDong3,yuanChengTvTingZhi3,yuanChengTvQiDong4,yuanChengTvTingZhi4,};
        initListener();
        sharedPreferences = this.getActivity().getSharedPreferences("qiDongZhuangTai",Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        AnNiuZhuangTai();
        requestQueue = Volley.newRequestQueue(getContext());
    }

    private void AnNiuZhuangTai() {
        if ( sharedPreferences.getInt("st1",0)==1){
            textViews[0].setBackgroundColor(getResources().getColor(R.color.changtong));
            textViews[1].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
        }else {
            textViews[1].setBackgroundColor(getResources().getColor(R.color.changtong));
            textViews[0].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
        }

        if ( sharedPreferences.getInt("st2",0)==1){
            textViews[2].setBackgroundColor(getResources().getColor(R.color.changtong));
            textViews[3].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
        }else {
            textViews[3].setBackgroundColor(getResources().getColor(R.color.changtong));
            textViews[2].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
        }

        if ( sharedPreferences.getInt("st3",0)==1){
            textViews[4].setBackgroundColor(getResources().getColor(R.color.changtong));
            textViews[5].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
        }else {
            textViews[5].setBackgroundColor(getResources().getColor(R.color.changtong));
            textViews[4].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
        }
        if ( sharedPreferences.getInt("st4",0)==1){
            textViews[6].setBackgroundColor(getResources().getColor(R.color.changtong));
            textViews[7].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
        }else {
            textViews[7].setBackgroundColor(getResources().getColor(R.color.changtong));
            textViews[6].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
        }



    }

    private void initListener() {
        for (int i=0;i<=7;i++){
            textViews[i].setOnClickListener(this);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.yuanCheng_tv_qiDong1:
                startCar(1);
                editor.putInt("st1",1).commit();
                textViews[0].setBackgroundColor(getResources().getColor(R.color.changtong));
                textViews[1].setBackgroundColor(getResources().getColor(R.color.listfontfocused));break;
            case R.id.yuanCheng_tv_tingZhi1:
                stopCar(1);
                editor.putInt("st1",0).commit();
                textViews[1].setBackgroundColor(getResources().getColor(R.color.changtong));
                textViews[0].setBackgroundColor(getResources().getColor(R.color.listfontfocused));break;

            case R.id.yuanCheng_tv_qiDong2:
                startCar(2);
                editor.putInt("st2",1).commit();
                textViews[2].setBackgroundColor(getResources().getColor(R.color.changtong));
                textViews[3].setBackgroundColor(getResources().getColor(R.color.listfontfocused));break;
            case R.id.yuanCheng_tv_tingZhi2:
                stopCar(2);
                editor.putInt("st2",0).commit();
                textViews[3].setBackgroundColor(getResources().getColor(R.color.changtong));
                textViews[2].setBackgroundColor(getResources().getColor(R.color.listfontfocused));break;

            case R.id.yuanCheng_tv_qiDong3:
                startCar(3);
                editor.putInt("st3",1).commit();
                textViews[4].setBackgroundColor(getResources().getColor(R.color.changtong));
                textViews[5].setBackgroundColor(getResources().getColor(R.color.listfontfocused));break;
            case R.id.yuanCheng_tv_tingZhi3:
                stopCar(3);
                editor.putInt("st3",0).commit();
                textViews[5].setBackgroundColor(getResources().getColor(R.color.changtong));
                textViews[4].setBackgroundColor(getResources().getColor(R.color.listfontfocused));break;

            case R.id.yuanCheng_tv_qiDong4:
                startCar(4);
                editor.putInt("st4",1).commit();
                textViews[6].setBackgroundColor(getResources().getColor(R.color.changtong));
                textViews[7].setBackgroundColor(getResources().getColor(R.color.listfontfocused));break;
            case R.id.yuanCheng_tv_tingZhi4:
                stopCar(4);
                editor.putInt("st4",0).commit();
                textViews[7].setBackgroundColor(getResources().getColor(R.color.changtong));
                textViews[6].setBackgroundColor(getResources().getColor(R.color.listfontfocused));break;
        }
    }

    private void stopCar(final int i) {
//        {"CarId":1, "CarAction":"Stop", "UserName":"user1"}
        String url = GetUrl.getUrl()+"action/SetCarMove.do";
        Map<String,Object> map = new HashMap<>();
        map.put("CarId",i);
        map.put("CarAction","Stop");
        map.put("UserName","user1");
        JSONObject jsonObject = new JSONObject(map);

        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                String string =jsonObject.toString();
                Gson gson =new Gson();
                BeanYuanChengZhuangTai beanYuanChengZhuangTai = gson.fromJson(string,BeanYuanChengZhuangTai.class);
                if (beanYuanChengZhuangTai.getERRMSG().equals("成功")){
                    Toast.makeText(getContext(),i+"号小车停止成功",Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(getContext(),i+"号小车停止失败，请重试",Toast.LENGTH_LONG).show();
                    if (i==1){
                        textViews[0].setBackgroundColor(getResources().getColor(R.color.changtong));
                        textViews[1].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                    }else if (i == 2){
                        textViews[2].setBackgroundColor(getResources().getColor(R.color.changtong));
                        textViews[3].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                    }else if (i == 3){
                        textViews[4].setBackgroundColor(getResources().getColor(R.color.changtong));
                        textViews[5].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                    }else if (i == 4){
                        textViews[6].setBackgroundColor(getResources().getColor(R.color.changtong));
                        textViews[7].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getContext(),i+"号小车停止失败，请重试",Toast.LENGTH_LONG).show();
                if (i==1){
                    textViews[0].setBackgroundColor(getResources().getColor(R.color.changtong));
                    textViews[1].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                }else if (i == 2){
                    textViews[2].setBackgroundColor(getResources().getColor(R.color.changtong));
                    textViews[3].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                }else if (i == 3){
                    textViews[4].setBackgroundColor(getResources().getColor(R.color.changtong));
                    textViews[5].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                }else if (i == 4){
                    textViews[6].setBackgroundColor(getResources().getColor(R.color.changtong));
                    textViews[7].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                }
            }
        });
        requestQueue.add(jsonRequest);

    } //stop

    private void startCar(final int i) {
        String url = GetUrl.getUrl()+"action/SetCarMove.do";
        Map<String,Object> map = new HashMap<>();
        map.put("CarId",i);
        map.put("CarAction","Start");
        map.put("UserName","user1");
        JSONObject jsonObject = new JSONObject(map);

        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                String string =jsonObject.toString();
                Gson gson =new Gson();
                BeanYuanChengZhuangTai beanYuanChengZhuangTai = gson.fromJson(string,BeanYuanChengZhuangTai.class);
                if (beanYuanChengZhuangTai.getERRMSG().equals("成功")){
                    Toast.makeText(getContext(),i+"号小车启动成功",Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(getContext(),i+"号小车启动失败，请重试",Toast.LENGTH_LONG).show();
                    if (i==1){
                        textViews[1].setBackgroundColor(getResources().getColor(R.color.changtong));
                        textViews[0].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                    }else if (i == 2){
                        textViews[3].setBackgroundColor(getResources().getColor(R.color.changtong));
                        textViews[2].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                    }else if (i == 3){
                        textViews[5].setBackgroundColor(getResources().getColor(R.color.changtong));
                        textViews[4].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                    }else if (i == 4){
                        textViews[7].setBackgroundColor(getResources().getColor(R.color.changtong));
                        textViews[6].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getContext(),i+"号小车启动失败，请重试",Toast.LENGTH_LONG).show();
                if (i==1){
                    textViews[1].setBackgroundColor(getResources().getColor(R.color.changtong));
                    textViews[0].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                }else if (i == 2){
                    textViews[3].setBackgroundColor(getResources().getColor(R.color.changtong));
                    textViews[2].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                }else if (i == 3){
                    textViews[5].setBackgroundColor(getResources().getColor(R.color.changtong));
                    textViews[4].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                }else if (i == 4){
                    textViews[7].setBackgroundColor(getResources().getColor(R.color.changtong));
                    textViews[6].setBackgroundColor(getResources().getColor(R.color.listfontfocused));
                }

            }
        });
        requestQueue.add(jsonRequest);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
